package edu.ncst.baseweb.service.impl.equ;

import cn.wintersun.basecommon.common.Result;
import edu.ncst.baseweb.dao.BorrowRecord;
import edu.ncst.baseweb.dao.equ.Equ;
import edu.ncst.baseweb.mapper.BorrowRecordMapper;
import edu.ncst.baseweb.mapper.EquMapper;
import edu.ncst.baseweb.service.intrer.equ.EquScrapService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class EquScrapServiceImpl implements EquScrapService {
    @Autowired
    private EquMapper equMapper;

    @Autowired
    private BorrowRecordMapper borrowRecordMapper;


    public Result<IPage<Equ>> list(Equ equ){
        QueryWrapper<Equ> queryWrapper = Wrappers.query();

        //设备名称查询
        if(StringUtils.isNotEmpty(equ.getName())){
            queryWrapper.like(Equ.COL_NAME,equ.getName());
        }
        //设备编号查询
        if(StringUtils.isNotEmpty(equ.getEquCode())){
            queryWrapper.like(Equ.COL_EQUCODE,equ.getEquCode());
        }
        //查询报废的设备
        queryWrapper.eq(Equ.COL_SCRAP,"1");

        Page<Equ> userPage = new Page<>(equ.getCurrent(), equ.getPageSize());
        Page<Equ> equPage = equMapper.selectPage(userPage, queryWrapper);

        return Result.ok(equPage);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Object> delete(String equId) throws Exception {
        if (StringUtils.isBlank(equId)){
            throw new Exception("被删除的id为空");
        }
        List<String> ids = Arrays.stream(equId.split(",")).collect(Collectors.toList());
        equMapper.deleteBatchIds(ids);

        QueryWrapper<BorrowRecord> query = Wrappers.query();
        query.in("user_id",ids);
        borrowRecordMapper.delete(query);

        return Result.failure(200, "成功！");

    }
}
